package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/13
 * @description ：
 * @version: 1.0
 */
@Component
public class SecurityUserDetail implements UserDetailsService {

	@Reference
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user =userService.findByUsername(username);
		if (user != null){
			System.out.println("username:"+username);
			List<GrantedAuthority> list = new ArrayList<>();
			Set<Role> roles = user.getRoles();
			for(Role role : roles){
				Set<Permission> permissions = role.getPermissions();
				// 角色关键词
				list.add(new SimpleGrantedAuthority(role.getKeyword()));
				for(Permission permission : permissions){
					//授权关键词
					list.add(new SimpleGrantedAuthority(permission.getKeyword()));
				}
			}
			UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
			return userDetails;
		}
		return null;
	}
}
